package md.NJavaBase;

import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

public class AdLoader implements ILoader {
    String Tag = "VideoAdLoader";
    public AdLoader(IAd ad,String tag)
    {
        m_ad = ad;
        Tag = tag;
    }

    public int getPriority() { return m_ad.getPriority(); }

    public IAd getAD() {  return m_ad;  }

    public AdState getState(){return m_State;}

    public boolean isInvalidated()
    {
        if(m_State!=AdState.Ready) return  false;

        boolean re = m_ad.isInvalidated();
        if(re) m_State = AdState.None;
        return re;
    }

    public void show(int channel)
    {
        if(m_State!=AdState.Ready) return;
        m_State = AdState.Showing;
        m_channel = channel;
        m_NeedReward = false;
        Log.d(Tag,"#2 NeedReward:false");
        m_ad.show();
    }

    public void reLoad(IAdLoaderCallback callback)
    {
        if(m_State!=AdState.None) {
            Log.d(Tag,"skip reload video!");
            return;
        }

        m_State = AdState.Loading;

        m_callback = callback;

        if(m_ad.isInitialized())//广告已经初始化完成
        {
            doLoad();//立即开始装载
        }else
        {
            MainLoop.StartLoop(new ILoop() {
                @Override
                public boolean Do() {
                    if(!m_ad.isInitialized()) //没有初始化好
                        return true;

                    doLoad();//装载
                    return false;
                }
            });
        }
    }

    //开始装载的时间点
    public long getStartLoadTime() { return m_lastTime; }

    void doLoad()
    {
        long now = System.currentTimeMillis();
        long lostTime = now - m_lastTime;
        long t = 5000 - lostTime;
        if(t>1000)//延迟load
        {
            Timer reloadTimer = new Timer();// 实例化Timer类
            class  overTimeTask extends TimerTask
            {
                public void run() {
                    class reloadRunnable implements Runnable
                    {
                        @Override public void run() {
                            m_lastTime = System.currentTimeMillis();
                            doLoad2();
                        }
                    }
                    NJavaBase.getActivity().runOnUiThread(new  reloadRunnable( ));
                    this.cancel();
                }
            }
            reloadTimer.schedule(new overTimeTask( ) , t);// 毫秒
        } else {//立即load
            m_lastTime = now;
            doLoad2();
        }
    }

    void doLoad2()
    {
        //用timer跟踪超时
        Timer reloadTimer = null;
        if(m_ad.needCheckLoadOvertime()) {
            reloadTimer = new Timer();// 实例化Timer类
            class overTimeTask extends TimerTask {
                public void run() {
                    class reloadRunnable implements Runnable {
                        @Override
                        public void run() {
                            Log.d(Tag, "load overtime!");
                            m_State = AdState.None;
                        }
                    }
                    NJavaBase.getActivity().runOnUiThread(new reloadRunnable());
                    this.cancel();
                }
            }
            reloadTimer.schedule(new overTimeTask(), 60000);// 毫秒
        }


        class loadAdCallback implements  IAdCallback
        {
            public  loadAdCallback(Timer overTimer )
            {
                m_overTimer = overTimer;
            }

            //广告加载成功
            public void onLoad()
            {
                class callbackRunnable implements Runnable
                {
                    @Override public void run() {
                        m_IsLoadSuccess = true;

                        if(m_overTimer!=null) { m_overTimer.cancel(); m_overTimer = null; }
                        Log.d(Tag,String.format("ad ready %s",m_ad.adName()) );
                        m_State = AdState.Ready;
                        m_callback.onLoad(); //回调加载成功
                    }
                }
                NJavaBase.getActivity().runOnUiThread(new  callbackRunnable( ));
            }

            //可获得奖励
            public void onReward()
            {
                class callbackRunnable implements Runnable
                {
                    @Override public void run() {
                        if(m_overTimer!=null) { m_overTimer.cancel(); m_overTimer = null; }
                        Log.d(Tag,String.format("ad reward %s",m_ad.adName()) );
                        m_NeedReward = true;
                        Log.d(Tag,"NeedReward:true");
                    }
                }
                NJavaBase.getActivity().runOnUiThread(new  callbackRunnable( ));
            }

            //广告被关闭
            public void onClose()
            {
                class callbackRunnable implements Runnable
                {
                    @Override public void run() {
                        if(m_overTimer!=null) { m_overTimer.cancel(); m_overTimer = null; }
                        Log.d(Tag,String.format("ad close %s NeedReward:%s",m_ad.adName(),m_NeedReward?"true":"false") );
                        m_State = AdState.None;
                        if(m_NeedReward)//存在奖励
                        {
                            m_NeedReward = false;
                            Log.d(Tag,"#1 NeedReward:false");

                            //奖励打点
                            //NJavaBase.trackEvent(String.format("%s_%d", m_ad.adName() , m_channel));

                            m_callback.onClose(true);//0
                        }else
                            m_callback.onClose(false);//1

                    }
                }
                NJavaBase.getActivity().runOnUiThread(new  callbackRunnable( ));
            }

            //加载错误
            public void onError(final String errCode)
            {
                class callbackRunnable implements Runnable
                {
                    @Override public void run() {
                        if(m_overTimer!=null) { m_overTimer.cancel(); m_overTimer = null; }
                        Log.d(Tag,String.format("ad load error %s",m_ad.adName()) );
                        m_callback.onError(errCode);//回调加载错误
                        m_State = AdState.None;
                    }
                }
                NJavaBase.getActivity().runOnUiThread(new  callbackRunnable( ));
            }

            Timer m_overTimer;
        }

        Log.d(Tag,String.format("Start loader %s",getAD().adName()));
        m_ad.reloadAd(new loadAdCallback(reloadTimer));
    }


    IAd m_ad;
    AdState m_State = AdState.None ;//广告状态
    int m_channel = 0;
    IAdLoaderCallback m_callback;//回调
    boolean m_NeedReward = false;
    long m_lastTime = 0;
    boolean m_IsLoadSuccess = false;//是否加载成功过
}
